<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave"> </transition>

    <!-- 房源数据分析卡片 -->
    <el-card shadow="hover" class="mb-[10px]">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-lg font-bold">房源数据分析</span>
          <!-- <el-button-group>
            <el-button type="primary" @click="refreshLeaseData" :loading="loading">
              <el-icon><Refresh /></el-icon>刷新数据
            </el-button>
          </el-button-group> -->
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover" class="h-full">
            <template #header>
              <div class="flex justify-between items-center">
                <span class="font-semibold">片区出租率</span>
                <el-select v-model="selectedDistrict1" placeholder="选择片区" style="width: 120px" size="small" @change="getdistrictOccupancyRate">
                  <el-option v-for="item in districtList" :key="item.id" :label="item.districtName" :value="item.id" />
                </el-select>
              </div>
            </template>
            <div ref="districtChartRef" style="height: 300px"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover" class="h-full">
            <template #header>
              <span class="font-semibold">楼宇出租率</span>
            </template>
            <div ref="buildingChartRef" style="height: 300px"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt-[10px]">
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <div class="flex items-center justify-between">
                <span class="font-semibold">租赁趋势分析</span>
                <div>
                  <el-select
                    v-model="selectedTrendDistrict"
                    style="width: 120px; margin-right: 10px"
                    placeholder="选择片区"
                    size="small"
                    @change="handleTrendDistrictChange(1)"
                  >
                    <el-option v-for="district in districtList" :key="district.id" :label="district.districtName" :value="district.id" />
                  </el-select>
                  <el-select
                    v-model="selectedTrendHousing"
                    placeholder="选择楼宇"
                    style="width: 120px; margin-right: 10px"
                    size="small"
                    clearable="true"
                    @change="handleTrendDistrictChange(2)"
                  >
                    <el-option v-for="item in buildList" :key="item.id" :label="item.housingName" :value="item.id" />
                  </el-select>
                  <el-select
                    v-model="selectedTrendFloor"
                    placeholder="选择楼层"
                    style="width: 120px"
                    size="small"
                    clearable="true"
                    @change="handleTrendDistrictChange(3)"
                  >
                    <el-option v-for="item in floorList" :key="item.id" :label="item.floorName" :value="item.id" />
                  </el-select>
                </div>
              </div>
            </template>
            <div ref="trendChartRef" style="height: 400px"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt-[10px]" v-if="false">
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <div class="flex items-center justify-between">
                <span class="font-semibold">历史出租率分析</span>
                <el-select v-model="selectedBuilding" placeholder="选择楼宇" @change="handleBuildingChange" style="width: 200px">
                  <el-option v-for="building in buildingList" :key="building.id" :label="building.buildingName" :value="building.id" />
                </el-select>
              </div>
            </template>
            <div ref="floorChartRef" style="height: 400px"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 申请人 -->
    <UserSelect ref="userSelectRef" :multiple="true" :data="selectUserIds" @confirm-call-back="userSelectCallBack"></UserSelect>
  </div>
</template>

<script setup lang="ts">
import { pageByTaskFinish } from '@/api/workflow/task';
import { TaskQuery, FlowTaskVO } from '@/api/workflow/task/types';
import workflowCommon from '@/api/workflow/workflowCommon';
import { RouterJumpVo } from '@/api/workflow/workflowCommon/types';
import {
  getLeaseStatistics,
  getDistrictOccupancyRate,
  getBuildingOccupancyRate,
  getFloorOccupancyRate,
  getDistrictLeaseTrend,
  getBuildingLeaseTrend
} from '@/api/system/tenant';
import { districtOccupancyRate, getParkFloor, housingOccupancyRate, leasingTrends, listDistrict, getBuildingList } from '@/api/system/building';
import { BuildingVO } from '@/api/system/building/types';
import * as echarts from 'echarts';
import { ref, onMounted, nextTick, onUnmounted, getCurrentInstance, toRefs } from 'vue';
import UserSelect from '@/components/UserSelect/index.vue';
import { UserVO } from '@/api/system/user/types';

//审批记录组件
const queryFormRef = ref<ElFormInstance>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status'));
const { wf_task_status } = toRefs<any>(proxy?.useDict('wf_task_status'));
const roleSetting = ref(localStorage.getItem('username'));
const userSelectRef = ref<InstanceType<typeof UserSelect>>();
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref<Array<any>>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 模型定义表格数据
const taskList = ref([]);
// 查询参数
const queryParams = ref<TaskQuery>({
  pageNum: 1,
  pageSize: 10,
  nodeName: undefined,
  flowName: undefined,
  flowCode: undefined,
  createByIds: []
});
//申请人id
const selectUserIds = ref<number[]>([]);
//申请人选择数量
const userSelectCount = ref(0);

// 图表相关变量
const districtChartRef = ref<HTMLElement>();
const buildingChartRef = ref<HTMLElement>();
const trendChartRef = ref<HTMLElement>();
const floorChartRef = ref<HTMLElement>();

// 图表实例变量
let districtChartInstance: echarts.ECharts | null = null;
let buildingChartInstance: echarts.ECharts | null = null;
let trendChartInstance: echarts.ECharts | null = null;
let floorChartInstance: echarts.ECharts | null = null;

const selectedBuilding = ref<string>('');
const buildingList = ref<BuildingVO[]>([]);
const selectedDistrict1 = ref();
const selectedDistrict = ref<string>('');
const districtList = ref<any[]>([]);
const districtDataList = ref<any[]>([]);
const buildList = ref([]);
const floorList = ref([]);
/** 搜索按钮操作 */
const handleQuery = () => {
  getFinishList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  queryParams.value.createByIds = [];
  userSelectCount.value = 0;
  selectUserIds.value = [];
  handleQuery();
};
// 多选框选中数据
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};
const getFinishList = () => {
  loading.value = true;
  pageByTaskFinish(queryParams.value).then((resp) => {
    taskList.value = resp.rows;
    total.value = resp.total;
    loading.value = false;
  });
};
/** 查看按钮操作 */
const handleView = (row: FlowTaskVO) => {
  const routerJumpVo = reactive<RouterJumpVo>({
    businessId: row.businessId,
    taskId: row.id,
    type: 'view',
    formCustom: row.formCustom,
    formPath: row.formPath
  });
  workflowCommon.routerJump(routerJumpVo, proxy);
};
//打开申请人选择
const openUserSelect = () => {
  userSelectRef.value.open();
};
//确认选择申请人
const userSelectCallBack = (data: UserVO[]) => {
  userSelectCount.value = 0;
  selectUserIds.value = [];
  queryParams.value.createByIds = [];

  if (data && data.length > 0) {
    userSelectCount.value = data.length;
    selectUserIds.value = data.map((item) => item.userId);
    queryParams.value.createByIds = selectUserIds.value;
  }
};

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    if (districtChartRef.value) {
      districtChartInstance = echarts.init(districtChartRef.value);
    }
    if (buildingChartRef.value) {
      buildingChartInstance = echarts.init(buildingChartRef.value);
    }
    if (trendChartRef.value) {
      trendChartInstance = echarts.init(trendChartRef.value);
    }
    if (floorChartRef.value) {
      floorChartInstance = echarts.init(floorChartRef.value);
    }
  });
};

// 加载楼宇列表
const loadBuildingList = async () => {
  // try {
  //   const response = await listBuilding({});
  //   buildingList.value = response.rows || [];
  //   if (buildingList.value.length > 0 && !selectedBuilding.value) {
  //     selectedBuilding.value = buildingList.value[0].id;
  //   }
  // } catch (error) {
  //   console.error('加载楼宇列表失败:', error);
  // }
};

// 加载房源数据
const loadLeaseData = async () => {
  try {
    loading.value = true;

    // 确保图表已初始化
    await nextTick();

    // 模拟数据 - 楼层出租率
  } catch (error) {
    console.error('加载房源数据失败:', error);
    // 如果API调用失败，使用模拟数据
    loadMockData();
  } finally {
    loading.value = false;
  }
};

// 加载模拟数据
const loadMockData = () => {
  // 加载片区数据
};

// 渲染各片区出租率图表（饼图）
const renderDistrictChart = (data: any[]) => {
  if (!districtChartRef.value) {
    console.error('districtChartRef is null');
    return;
  }

  if (!districtChartInstance) {
    console.warn('districtChartInstance is null, attempting to initialize...');
    if (districtChartRef.value) {
      districtChartInstance = echarts.init(districtChartRef.value);
    }
  }

  if (!districtChartInstance) {
    console.error('Failed to initialize districtChartInstance');
    return;
  }

  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];

  const option = {
    title: {
      text: `${data[0].districtName} 统计`,
      left: 'center',
      top: 5, // 增加顶部留白至50px
      textStyle: {
        fontSize: 11,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        // const total = data[0].totalArea + data[0].leaseArea;
        const percent = ((data[0].leaseArea / data[0].totalArea) * 100).toFixed(2);
        return `
            <div style="padding: 8px;">
              <div style="font-weight: bold; margin-bottom: 4px;">${params.name}</div>
              <div>面积: ${params.data.value.toLocaleString()}m²</div>
              <div>比例: ${percent}%</div>
            </div>
          `;
      }
    },
    legend: {
      orient: 'horizontal',
      bottom: 0, // 增加底部留白至50px
      left: 'center',
      textStyle: {
        fontSize: 12
      }
    },
    color: ['#1890ff', '#fa8c16'], // 蓝色表示总面积，橙色表示租赁面积
    series: [
      {
        name: '面积比例',
        type: 'pie',
        radius: ['20%', '50%'], // 进一步减小半径增加四周留白
        center: ['50%', '50%'], // 保持居中
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {d}%',
          fontSize: 12
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: true,
          length: 20,
          length2: 5,
          smooth: true
        },
        data: [
          {
            name: '未租赁面积',
            value: data[0].totalArea - data[0].leaseArea
          },
          {
            name: '租赁面积',
            value: data[0].leaseArea
          }
        ]
      }
    ]
  };
  districtChartInstance.setOption(option);
};

// 渲染各楼宇出租率图表
const renderBuildingChart = (data: any[]) => {
  if (!buildingChartRef.value) {
    console.error('buildingChartRef is null');
    return;
  }

  if (!buildingChartInstance) {
    console.warn('buildingChartInstance is null, attempting to initialize...');
    if (buildingChartRef.value) {
      buildingChartInstance = echarts.init(buildingChartRef.value);
    }
  }

  if (!buildingChartInstance) {
    console.error('Failed to initialize buildingChartInstance');
    return;
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: data.map((item) => item.housingName),
      axisLabel: {
        rotate: 30,
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      name: '出租率(%)',
      max: 100
    },
    dataZoom: [
      {
        type: 'slider',
        xAxisIndex: 0,
        start: 0,
        end: data.length > 5 ? (5 / data.length) * 100 : 100,
        handleSize: '100%',
        handleStyle: {
          color: '#fff',
          borderColor: '#188df0'
        }
      }
    ],
    series: [
      {
        name: '出租率',
        type: 'bar',
        data: data.map((item) => item.occupancyRate),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}%'
        }
      }
    ]
  };
  buildingChartInstance.setOption(option);
};

// 渲染租赁趋势图表
const renderTrendChart = (data: any[]) => {
  if (!trendChartRef.value) {
    console.error('trendChartRef is null');
    return;
  }

  if (!trendChartInstance) {
    console.warn('trendChartInstance is null, attempting to initialize...');
    if (trendChartRef.value) {
      trendChartInstance = echarts.init(trendChartRef.value);
    }
  }

  if (!trendChartInstance) {
    console.error('Failed to initialize trendChartInstance');
    return;
  }

  const option = {
    title: {
      text: '租赁趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['租赁比例'],
      top: 30
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.map((item) => item.month)
    },
    yAxis: [
      {
        type: 'value',
        name: '出租率%',
        position: 'left'
      },
      {
        type: 'value',
        name: '数量',
        position: 'right'
      }
    ],
    series: [
      {
        name: '租赁率',
        type: 'line',
        smooth: true,
        data: data.map((item) => item.occupancyRate),
        itemStyle: { color: '#5470c6' }
      }
    ]
  };
  trendChartInstance.setOption(option);
};

// 渲染楼层出租率图表
const renderFloorChart = (data: any[]) => {
  if (!floorChartRef.value) {
    console.error('floorChartRef is null');
    return;
  }

  if (!floorChartInstance) {
    console.warn('floorChartInstance is null, attempting to initialize...');
    if (floorChartRef.value) {
      floorChartInstance = echarts.init(floorChartRef.value);
    }
  }

  if (!floorChartInstance) {
    console.error('Failed to initialize floorChartInstance');
    return;
  }

  const option = {
    title: {
      text: '各楼层出租率',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      }
    },
    xAxis: {
      type: 'category',
      data: data.map((item) => `F${item.floorNumber}`),
      name: '楼层'
    },
    yAxis: {
      type: 'value',
      name: '出租率(%)',
      max: 100
    },
    series: [
      {
        name: '出租率',
        type: 'line',
        smooth: true,
        data: data.map((item) => item.occupancyRate),
        areaStyle: {
          opacity: 0.3
        },
        markLine: {
          data: [
            {
              type: 'average',
              name: '平均值'
            }
          ]
        }
      }
    ]
  };
  floorChartInstance.setOption(option);
};

// 刷新房源数据
const refreshLeaseData = () => {
  loadLeaseData();
};

// 楼宇选择变化
const handleBuildingChange = (buildingId: string) => {
  selectedBuilding.value = buildingId;
  loadFloorOccupancyData();
};

// 片区选择变化
const handleDistrictChange = (value: string) => {
  selectedDistrict.value = value;
};

// 加载楼层出租率数据
const loadFloorOccupancyData = async () => {
  if (!selectedBuilding.value) return;

  try {
    const floorData = await getFloorOccupancyRate(selectedBuilding.value);
    renderFloorChart(floorData.data || []);
  } catch (error) {
    console.error('加载楼层出租率失败:', error);
  }
};

// 窗口大小改变时重新调整图表大小
const handleResize = () => {
  districtChartInstance?.resize();
  buildingChartInstance?.resize();
  trendChartInstance?.resize();
  floorChartInstance?.resize();
};

onMounted(() => {
  getDistrictList();
  getFinishList();
  loadBuildingList();
  getdistrictOccupancyRate();
  gethousingOccupancyRate();
  getleasingTrends({});
  // 确保DOM完全加载后再初始化图表和加载数据
  nextTick(() => {
    initCharts();
    // 延迟加载数据，确保图表已初始化
    setTimeout(() => {
      loadLeaseData();
    }, 100);
  });

  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  districtChartInstance?.dispose();
  buildingChartInstance?.dispose();
  trendChartInstance?.dispose();
  floorChartInstance?.dispose();
});

/** 查询区域列表 */
const getDistrictList = async () => {
  try {
    const res = await listDistrict({ pageNum: 1, pageSize: 100 });
    districtList.value = res.rows;
    selectedDistrict1.value = res.rows[0].id;
    // changeDistrict();
    getdistrictOccupancyRate();
  } finally {
  }
};

const changeDistrict = async () => {
  if (districtDataList.value.length == 0) return;
  // 根据selectedDistrict1筛选匹配id的数据
  const selectedData = districtDataList.value.find((item) => item.id === selectedDistrict1.value);
  console.log('selectedData', selectedData);
  if (selectedData) {
    renderDistrictChart([selectedData]);
  }
};

/** 查询测试单列表 */
const getdistrictOccupancyRate = async () => {
  const res = await districtOccupancyRate({ districtId: selectedDistrict1.value });
  if (res.code == 200) {
    districtDataList.value = res.data;
    // console.log('districtDataList.value', districtDataList.value);
    changeDistrict();
  }
};

const getBuildingListApiByDistrictId = async () => {
  try {
    const res = await getBuildingList({ pageNum: 1, pageSize: 100, districtId: selectedTrendDistrict.value });
    buildList.value = res.rows;

    // 提取并生成楼层列表
    floorList.value = [];
    for (var i = 1; i < buildList.value.length + 1; i++) {
      floorList.value.push({
        id: i,
        value: `第${i}层`
      });
    }
  } finally {
  }
};

const selectedTrendDistrict = ref('');
const selectedTrendHousing = ref('');
const selectedTrendFloor = ref('');
const handleTrendDistrictChange = async (type: any) => {
  if (type == 1) {
    selectedTrendHousing.value = '';
    selectedTrendFloor.value = '';
    getBuildingListApiByDistrictId();
  }
  if (type == 2) {
    selectedTrendFloor.value = '';
    changeFloors();
  }
  const param = {
    districtId: selectedTrendDistrict.value,
    housingId: selectedTrendHousing.value,
    floor: selectedTrendFloor.value
  };

  getleasingTrends(param);
};

const changeFloors = async () => {
  floorList.value = [];
  const res = await getParkFloor({ housingId: selectedTrendHousing.value });
  if (res.code === 200) {
    floorList.value = res.data;
  }
};

const gethousingOccupancyRate = async () => {
  const res = await housingOccupancyRate({});
  if (res.code == 200) {
    res.data.forEach((item) => {
      item.occupancyRate = item.totalArea === 0 ? 0 : Number(((item.leaseArea / item.totalArea) * 100).toFixed(1));
    });
    console.log('gethousingOccupancyRate.value', res.data);
    renderBuildingChart(res.data);
  }
};
const getleasingTrends = async (param: any) => {
  const res = await leasingTrends(param);
  if (res.code == 200) {
    res.data.forEach((item) => {
      item.occupancyRate = item.totalArea === 0 ? 0 : Number(((item.leaseArea / item.totalArea) * 100).toFixed(1));
    });
    renderTrendChart(res.data);
  }
};
</script>
